<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="用户名" path="name">
          <n-input v-model:value="formValue.name" disabled="true"/>
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input v-model:value="formValue.email"/>
        </n-form-item>
        <n-form-item label="原密码" path="oldpass">
          <n-input v-model:value="formValue.oldpass" type="password" show-password-on="mousedown"/>
        </n-form-item>
        <n-form-item label="新密码" path="newpass">
          <n-input v-model:value="formValue.newpass" type="password" show-password-on="mousedown"/>
        </n-form-item>
        <n-form-item label="确认新密码" path="newpass_confirm">
          <n-input v-model:value="formValue.newpass_confirm" type="password" show-password-on="mousedown"/>
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref ,onBeforeMount} from 'vue';
  import { useMessage } from 'naive-ui';
  import {http} from "@/utils/http/axios";
  import {useRouter,useRoute} from "vue-router";
 const router=useRouter()
  const route=useRoute()
  const rules = {
    name: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
    oldpass: {
      required: true,
      message: '请输入旧密码',
      trigger: 'blur',
    },
    newpass: {
      required: true,
      message: '请输入新密码',
      trigger: 'input',
    },
    newpass_confirm: {
      required: true,
      message: '请确认密码',
      trigger: 'input',
    },
  };
  const formRef: any = ref(null);
  const message = useMessage();

  let formValue = reactive({
    id:"",
    email:"",
    name: '',
    oldpass: '',
    newpass: '',
    newpass_confirm: '',
  });
  function getUserInfo(){
    http.request({
      url:"/api/userinfo",
      method:"post",
    }).then((res)=>{
      formValue=Object.assign(formValue,res);
    })
  }
  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        if(formValue.newpass!==formValue.newpass_confirm){
          window['$message'].error("二次输入的密码不一至！请检查");
          return;
        }
        http.request({
          url:"/api/userchange",
          method:"post",
          data:formValue
        }).then(()=>{
          window['$message'].success('更新成功');
          formValue.newpass="";
          formValue.oldpass="";
          formValue.newpass_confirm="";
        }).catch((err)=>{
          window['$message'].error(err);
        })
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }
  onBeforeMount(()=>{
    getUserInfo();
  })
</script>
